package cn.yangliu.poi.tools;

import cn.yangliu.comm.tools.DateUtils;
import cn.yangliu.comm.tools.FileUtils;
import cn.yangliu.comm.tools.ReflectUtils;
import cn.yangliu.comm.tools.StringUtils;
import cn.yangliu.poi.PoiConst;
import com.csvreader.CsvWriter;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 作者 杨柳
 * 创建时间 2017-07-16 15:37
 */
public class CsvUtils implements ExportUtils {

    private static final CsvUtils utils = new CsvUtils();

    private CsvUtils() {
    }

    public static void createCsv(LinkedHashMap<String, String> mapping, List<?> dataList, String targetFile) {
        createCsv(mapping, dataList, targetFile, null);
    }

    public static void createCsv(LinkedHashMap<String, String> mapping, List<?> dataList, String targetFile, List<LinkedHashMap<String, Object>> otherDatas) {
        CsvWriter writer = new CsvWriter(targetFile, ',', Charset.forName("UTF-8"));
        try {
            Set<String> titles = mapping.keySet();

            String[] allTitles = new String[titles.size()];
            int index = 0;
            for (String title : titles) { //设置标题
                allTitles[index] = title;
                index++;
            }
            writer.writeRecord(allTitles);

            int max_count = dataList.size() < PoiConst.MAX_EXCEL_COUNT ? dataList.size() : PoiConst.MAX_EXCEL_COUNT;
            for (int i = 0; i < max_count; i++) {
                Object obj = dataList.get(i);
                Iterator<Map.Entry<String, String>> it = mapping.entrySet().iterator();
                String[] values = new String[titles.size()];
                index = 0;
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    String fieldName = entry.getValue();
                    Object value = ReflectUtils.getValueByGetMethod(fieldName, obj);
                    Field field = ReflectUtils.getField(fieldName, obj);
                    String stringValue = utils.getStringValue(value, field);
                    values[index] = stringValue;
                    index++;
                }
                writer.writeRecord(values);
            }

            /**
             * 其他不规则数据
             */
            if (otherDatas != null) {
                for (int i = 0; i < otherDatas.size(); i++) {
                    LinkedHashMap<String, Object> dataMap = otherDatas.get(i);
                    Set<String> keys = dataMap.keySet();
                    String[] lastLineData = new String[keys.size() * 2];
                    index = 0;
                    for (String key : keys) {
                        lastLineData[index] = key;
                        index++;
                        lastLineData[index] = dataMap.get(key).toString();
                        index++;
                    }
                    writer.writeRecord(lastLineData);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public static void download(HttpServletResponse response, LinkedHashMap<String, String> mapping, List<?> dataList, String filePath) {
        String targetFile = filePath.concat(DateUtils.date2String(new Date(), DateUtils.DATE).concat(StringUtils.getUUID()).concat(".csv"));
        //创建临时文件
        createCsv(mapping, dataList, targetFile);
        //下载
        FileUtils.download(response, "download.csv", targetFile);
        //删除临时文件
        FileUtils.deleteFile(targetFile);
    }

    public static void download(HttpServletResponse response, LinkedHashMap<String, String> mapping, List<?> dataList, String filePath, List<LinkedHashMap<String, Object>> list) {
        String targetFile = filePath.concat(DateUtils.date2String(new Date(), DateUtils.DATE).concat(StringUtils.getUUID()).concat(".csv"));
        //创建临时文件
        createCsv(mapping, dataList, targetFile, list);
        //下载
        FileUtils.download(response, "download.csv", targetFile);
        //删除临时文件
        FileUtils.deleteFile(targetFile);
    }
}
